﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EmoneyWeiXinEntity;
using EmoneyWeiXinDAL;
using System.Data;
using EmoneyWeiXinCommon;
using Newtonsoft.Json.Linq;
namespace EmoneyWeiXinBLL
{
    public class UserGroupManagerBLL
    {
        public static List<UserGroupManagerEntity> getUserGroupManagerList(int pindex, int psize, int weixinid, out int total)
        {
            return UserGroupManagerDal.getUserGroupManagerList(pindex, psize, weixinid, out  total);
        }
        public static List<UserGroupManagerEntity> getUserGroupManagerList(int weixinid)
        {
            return UserGroupManagerDal.getUserGroupManagerList(weixinid);
        }
        //获取省份列表
        public static DataSet GetProvinceList()
        {
            return UserGroupManagerDal.GetProvinceList();
        }
        //根据身份获取城市列表
        public static DataSet GetCityListByPname(string pname)
        {
            return UserGroupManagerDal.GetCityListByPname(pname);
        }

        public static UserGroupManagerEntity getUserGroupManagerListByID(int id)
        {
            var list = UserGroupManagerDal.getUserGroupManagerListByID(id);
            if (list != null && list.Count > 0)
                return list[0];
            else
                return new UserGroupManagerEntity();
        }

        public static int UpdateUserGroupManager(UserGroupManagerEntity obj)
        {
            return UserGroupManagerDal.UpdateUserGroupManager(obj);
        }
        public static int DeleteUserGroupManager(int id)
        {
            return UserGroupManagerDal.DeleteUserGroupManager(id);
        }



        /// <summary>
        /// 在微信平台上创建组
        /// </summary>
        /// <param name="weixinid"></param>
        /// <param name="groupname"></param>
        /// <returns>分组id，由微信分配</returns>
        public static string CreateGroup(int weixinid, string groupname)
        {
            //https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN
            //{"group":{"name":"test"}}
            string url = Config.WeiXin_ApiUrl + "groups/create";
            var msgJson = "{\"group\":{\"name\":\"" + groupname + "\"}}";
            string funcRet = "";
            try
            {
                weixinUserBLL bll = new weixinUserBLL();
                string appid = bll.getWeixinUserByID(weixinid).AppId;
                string appsercret = bll.getWeixinUserByID(weixinid).AppSecret;
                string token = TokenHelper.GetToken(appid, appsercret);
                if (string.IsNullOrEmpty(token))
                {
                    return funcRet;
                }
                Dictionary<string, string> urlParams = new Dictionary<string, string>();
                urlParams.Add("access_token", token);

                // MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + url + "||" + msgJson + "||");
                string ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                //MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + ret + "||");
                if (ret.IndexOf("{\"errcode\":40001") != -1)
                {
                    TokenHelper.ClearToken();
                    urlParams = new Dictionary<string, string>();
                    urlParams.Add("access_token", TokenHelper.GetToken(appid, appsercret));
                    ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                }

                JObject jObj = JObject.Parse(ret);
                if (jObj != null)
                {
                    funcRet = ((dynamic)jObj).group.id;
                }
                ////MyTrace.get().add("funcRet=" + funcRet);
            }
            catch (Exception)
            {
                ////MyTrace.get().add("CreateTwoCodeTicket-Exception:" + ex.Message + " url=" + url + " msgJson=" + msgJson + " scene_id=" + scene_id);
            }
            return funcRet;
        }
        /// <summary>
        /// 修改分组
        /// </summary>
        /// <param name="weixinid"></param>
        /// <param name="groupid"></param>
        /// <param name="groupname"></param>
        /// <returns></returns>
        public static string EditGroup(int weixinid, int groupid, string groupname)
        {
            string url = Config.WeiXin_ApiUrl + "groups/update";
            var msgJson = "{\"group\":{\"id\":" + groupid + ",\"name\":\"" + groupname + "\"}}}";
            string funcRet = "";
            try
            {
                weixinUserBLL bll = new weixinUserBLL();
                string appid = bll.getWeixinUserByID(weixinid).AppId;
                string appsercret = bll.getWeixinUserByID(weixinid).AppSecret;
                string token = TokenHelper.GetToken(appid, appsercret);
                if (string.IsNullOrEmpty(token))
                {
                    return funcRet;
                }
                Dictionary<string, string> urlParams = new Dictionary<string, string>();
                urlParams.Add("access_token", token);

                // MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + url + "||" + msgJson + "||");
                string ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                //MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + ret + "||");
                if (ret.IndexOf("{\"errcode\":40001") != -1)
                {
                    TokenHelper.ClearToken();
                    urlParams = new Dictionary<string, string>();
                    urlParams.Add("access_token", TokenHelper.GetToken(appid, appsercret));
                    ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                }

                JObject jObj = JObject.Parse(ret);
                if (jObj != null)
                {
                    JToken jToken;
                    if (jObj.TryGetValue("errmsg", out jToken))
                    {
                        funcRet = jObj["errmsg"].ToString().Replace("\"", "");
                        ////MyTrace.get().add("调用web服务器-GetTwoCodeTicket-errcode=" + funcRet);
                    }
                }
                ////MyTrace.get().add("funcRet=" + funcRet);
            }
            catch (Exception)
            {
                ////MyTrace.get().add("CreateTwoCodeTicket-Exception:" + ex.Message + " url=" + url + " msgJson=" + msgJson + " scene_id=" + scene_id);
            }
            return funcRet;
        }

        /// <summary>
        /// 批量移动用户分组
        /// </summary>
        /// <param name="weixinid"></param>
        /// <param name="openidlist"></param>
        /// <param name="to_groupid"></param>
        /// <returns></returns>
        public static string BatchMoveUserGroup(int weixinid, string openidlist, int to_groupid)
        {
            //https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=ACCESS_TOKEN
            //{"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}

            //            http请求方式: POST（请使用https协议）
            //https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=ACCESS_TOKEN
            //POST数据格式：json
            //POST数据例子：{"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}

            string url = Config.WeiXin_ApiUrl + "groups/members/batchupdate";
            var msgJson = "{\"openid_list\":[" + openidlist + "],\"to_groupid\":" + to_groupid + "}";
            string funcRet = "";
            try
            {
                weixinUserBLL bll = new weixinUserBLL();
                weixinUserEntity user = bll.GetWeixinUserFromCache(weixinid.ToString());
                string appid = user.AppId;
                string appsercret = user.AppSecret;
                string token = TokenHelper.GetToken(appid, appsercret);
                if (string.IsNullOrEmpty(token))
                {
                    return funcRet;
                }
                Dictionary<string, string> urlParams = new Dictionary<string, string>();
                urlParams.Add("access_token", token);

                // MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + url + "||" + msgJson + "||");
                string ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                //MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + ret + "||");
                if (ret.IndexOf("{\"errcode\":40001") != -1)
                {
                    TokenHelper.ClearToken(appid);
                    urlParams = new Dictionary<string, string>();
                    urlParams.Add("access_token", TokenHelper.GetToken(appid, appsercret));
                    ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                }

                JObject jObj = JObject.Parse(ret);
                if (jObj != null)
                {
                    JToken jToken;
                    if (jObj.TryGetValue("errmsg", out jToken))
                    {
                        funcRet = jObj["errmsg"].ToString().Replace("\"", "");
                        ////MyTrace.get().add("调用web服务器-GetTwoCodeTicket-errcode=" + funcRet);
                    }
                }
                ////MyTrace.get().add("funcRet=" + funcRet);
            }
            catch (Exception)
            {
                ////MyTrace.get().add("CreateTwoCodeTicket-Exception:" + ex.Message + " url=" + url + " msgJson=" + msgJson + " scene_id=" + scene_id);
            }
            return funcRet;
        }


        public static DataSet GetOpenidListByGroupId(string weixinId, string groupId)
        {
            return UserGroupManagerDal.GetOpenidListByGroupId(weixinId, groupId);
        }

        public static UserGroupManagerEntity GetOne(string groupId) 
        {
            return UserGroupManagerDal.GetOne(groupId);
        }
    }
}
